
# 导包date
from pyecharts.charts import Bar, Timeline
from pyecharts.options import TitleOpts,LabelOpts
from pyecharts.globals import ThemeType

# 读取文件
with open("D:/python-learn/data/2015-2022中国汽车分厂商每月销售表.csv", "r", encoding="UTF-8") as f:
    data = f.readlines()

# 删除第一行数据
data.pop(0)

# 提取所需数据
data_dict = {}
for data_str in data:
    data_list = data_str.split(",")
    date_str = data_list[0]
    maker = data_list[1]
    sales = int(data_list[2])

    # 转换日期为 (year, month) 元组
    year,month = map(int, date_str.split('.'))
    date_key = (year, month)

    # 将数据存入字典
    if date_key in data_dict:
        data_dict[date_key].append([maker, sales])
    else:
        data_dict[date_key] = []
        data_dict[date_key].append([maker, sales])

# 对日期进行排列
def sales_data(data_dict):
    sorted_date = sorted(data_dict.keys())
    x_result = []
    y_result = []
    # 对每个时段里厂商销量进行排序
    for date_key in sorted_date:
        data_dict[date_key] = sorted(data_dict[date_key], key = lambda element : element[1], reverse=True)

    # 取出前20的厂商
        process_sale_maker = data_dict[date_key][0:20]
        x_data = []
        y_data = []
        for every_maker in process_sale_maker:
            x_data.append(every_maker[0])
            y_data.append(every_maker[1])
        x_result.append(x_data)
        y_result.append(y_data)
    return x_result, y_result, sorted_date
x_data, y_data, dates = sales_data(data_dict)

# 建立时间线对象
time_line = Timeline({"theme":ThemeType.DARK})

# 添加柱状图数据
for date, x, y in zip(dates, x_data, y_data):
    x.reverse()
    y.reverse()
    bar = Bar()
    bar.add_xaxis(x)
    bar.add_yaxis("销量", y, label_opts=LabelOpts(position="right"))
    bar.reversal_axis()
    bar.set_global_opts(
        title_opts=TitleOpts(is_show=True,
                             pos_bottom="88%",
                             pos_left="center")
    )
# 添加时间线数据
    time_line.add(bar, str(date))

# 设置时间线对象
time_line.add_schema(
    is_timeline_show=True,
    is_auto_play=True,
    is_loop_play=True,
    play_interval=1000
)

time_line.render("2015-2022年中国汽车分厂商销量对比.html")